package com.pospi.pospihold.ui.pay_ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.chinaums.mpos.aar.IUmsPayListener;
import com.chinaums.mpos.aar.UmsPayManager;
import com.chinaums.mpos.service.IUmsMposResultListener;
import com.lany.sp.SPHelper;
import com.pospi.pospihold.App;
import com.pospi.pospihold.util.Constant;
import com.pospi.pospihold.util.GetData;
import com.pospi.pospihold.util.SignExample;
import com.tsy.sdk.myokhttp.response.RawResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import static com.pospi.pospihold.ui.pay_ui.UnionConfig.MERCHANTCODE;
import static com.pospi.pospihold.ui.pay_ui.UnionConfig.TERMINALCODE;

/**
 * Created by acer on 2018/9/29.
 */

public class PayUtil {
    private Handler handler;
    private String je;
    private int payCode;
    private Context context;
    private String union_orderid ="";
    public final static int SUCCESS = 1;
    public final static int FAILED = 0;
    public final static int UPSUCCESS = 3;
    public final static int UPFAILED = 2;
    public PayUtil(Handler handler, String je, int payCode) {
        this.handler = handler;
        this.je = je;
        this.payCode = payCode;
    }
    public PayUtil(Handler handler, String je, int payCode , Context context) {
        this.handler = handler;
        this.je = je;
        this.payCode = payCode;
        this.context = context;
    }

    public void startCash(){
        payCash();
    }
    public void startWX(String code){
    }
    public void startAliAndWx(String code){
        unionPay(code,je,GetData.getYYMMDDhhmmss());
    }
    public void startCard(){
    }
    private void payCash() {
        sendSMsg();
    }
    public void startPayBlank(){
        // Android sdk集成示例
        UmsPayManager umsPayManager = UmsPayManager.getInstance();
        Bundle bundle = new Bundle();
        // callbackFunc为回调方法，会返回ums_response字段
        bundle.putString("ums_request", getJson());
        umsPayManager.umspay(context, bundle, new IUmsPayListener() {
            @Override
            public void onReturnResult(Bundle bundle) {
                // 处理接口返回结果
                String umsResponse = bundle.getString("ums_response");
                Log.i("data", "返回信息---> " + umsResponse);

                // 以下是演示ums_response的处理
                if (umsResponse != null && !"".equals(umsResponse)) {
                    try {
                        JSONObject jsStr = new JSONObject(umsResponse);
                        if ("ums.trade.pay.wo8y2lsu".equals(jsStr.optString("business_id"))
                                && "MC_110001".equals(jsStr.optString("main_code"))) {
                            Message message = Message.obtain();
                            message.what = SUCCESS;
                            handler.sendMessage(message);
                        } else {
                            Message message = Message.obtain();
                            message.what = FAILED;
                            message.obj = jsStr.optString("sub_msg");
                            handler.sendMessage(message);
                        }
                    } catch (Exception e) {

                    }

                } else {

                }
            }
        });


    }

    private String getJson() {
        JSONObject object = new JSONObject();
        try {
            object.put("business_id", "ums.trade.pay.wo8y2lsu");
            JSONObject data = new JSONObject();
            data.put("billsMID", "shouji000000004");
            data.put("billsTID", "sj000004");
//            data.put("billsMID", "898319973720016");
//            data.put("billsTID", "00000001");
            data.put("merOrderId", "1995"+GetData.getYYMMDDhhmmss());
            data.put("merOrderDesc", "buy haose");
            data.put("amount", "1");
            data.put("operator", "000001");

            data.put("consumerPhone", "17798237790");
            data.put("payType", "BANKCARD");
//            data.put("memo", "");
//            data.put("orgCode", "D2573101");
//            data.put("isShowOrderInfo", "true");
//
//            data.put("isShowEVoucherPage", "true");
//            data.put("saleSlipFavorite", "defaultType");
//            data.put("unsupportedCardType", "");
//            data.put("couponType", "0");
//            data.put("couponNo", "");
//            data.put("memo", "");


            object.put("data", data);
            String privateKeyP = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIXe8atk1cQc/3br46uTZpWpydNd4/KIg0tT2L4T7+WAD6YdpFUClIt8FqyPi1n1GTMSNDS/G0UuEvYFkGLMxjWUFBVbM9O0HJU8mkzMm2JOEdFW7pKWpP1cZWipz67CtGw1KIwyCmqcOjr9q0GO6Vj64WmH/CPDcMi+PQCEmn9zAgMBAAECgYA8ao50xJA47sFYYUMhpudQOg1M5/288mEWuOODfSnyUGY/mPcWKpDxlnIBNNM2KQhTZS7Mc0cSZKXIBGDSRgpZa+Mwn664nDbvZi1uv75G5QtKjA7ZOC4nYIab2oOPC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pT7KawJAKbTXxcCBewV+gsJsi/gXdMcvMzSf6oQjh+L70ZzbPun3A7WViiGsBPM5BI/fBPuD8DwUDOxL/7BOV0QRLw7mYwJANhj2sQ1uLvZTI5wqofcTSiEJ0J7KBunnN29gODNpxMNePrQOpeAt6Xk49ORNxLDdbubpV+jR6AvS9l50BnWffwJBAM7kuOxHtjjhDd7U5m3U2Ud9Wbg26ZbFnGD0BE2vQhNMSAt/GkKDj/mJi4zlCGjolk7dNP64NtipukcqXTaxZa8=";            String originalStr = SignExample.buildSignStringFromJson(data);
            String sign = SignExample.doSign(originalStr, privateKeyT);
            JSONObject extend = new JSONObject();
            JSONObject object1 = new JSONObject();
            object1.put("BJP", "1000A4Z301000212345600001");
            extend.put("extension", object1);
            object.put("extend_params", extend);
            object.put("sign", sign);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("data", object.toString());
        return object.toString();
    }

    private void sendSMsg(){
        Message message = Message.obtain();
        message.what = SUCCESS;
        handler.sendMessage(message);
    }
    private void sendFMsg(String msg){
        Message message = Message.obtain();
        message.what = FAILED;
        message.obj = msg;
        handler.sendMessage(message);
    }
    public void unionPay(String code,String money,String orderId){
        int amount  = (int) (Double.parseDouble(money)*100);
        JSONObject object = new JSONObject();
        try {
            object.put("merchantCode", SPHelper.getInstance().getString(MERCHANTCODE,""));
            object.put("terminalCode", SPHelper.getInstance().getString(TERMINALCODE,""));
            object.put("transactionAmount", amount);
            object.put("transactionCurrencyCode", "156");
            object.put("merchantOrderId",SPHelper.getInstance().getString(MERCHANTCODE,"")+ GetData.getStringRandom(6)+orderId);
//            object.put("systemTraceNum", GetData.getHHmmssTime());
            object.put("merchantRemark", GetData.getStringRandom(10));
            object.put("payMode", "E_CASH");
            object.put("payCode", code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i("pay", object.toString());
        App.getInstance().getMyOkHttp().post()
                .url(UnionConfig.URL_PAY)
                .jsonParams(object.toString())
                .addHeader("Authorization","OPEN-ACCESS-TOKEN AccessToken="+ SPHelper.getInstance().getString(UnionConfig.TOKEN_MSG))
                .enqueue(new RawResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, String response) {
                        Log.i("pay", response);
                        try {
                            JSONObject json = new JSONObject(response);
                            String errCode = json.getString("errCode");
                            String errInfo = json.getString("errInfo");

                            if (errCode.equals("00")) {
                                union_orderid = json.getString("orderId");
                                Message message = Message.obtain();
                                message.what = SUCCESS;
                                message.obj = union_orderid;
                                handler.sendMessage(message);
                            } else {
                                Message message = Message.obtain();
                                message.what = FAILED;
                                message.obj = errInfo;
                                handler.sendMessage(message);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(int statusCode, String error_msg) {
                        Log.i("pay", error_msg);
                        Message message = Message.obtain();
                        message.what = FAILED;
                        message.obj = error_msg;
                        handler.sendMessage(message);
                    }
                });
    }

}
